#!/usr/bin/env python3
"""
轻量级Web服务器，用于部署MCP系统的前端界面
"""

import os
import sys
import logging
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler
import socketserver
import threading
import time
import webbrowser

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class CORSHTTPRequestHandler(SimpleHTTPRequestHandler):
    """支持CORS的HTTP请求处理器"""
    
    def end_headers(self):
        """添加CORS头"""
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        super().end_headers()
    
    def do_OPTIONS(self):
        """处理OPTIONS预检请求"""
        self.send_response(200)
        self.end_headers()
    
    def log_message(self, format, *args):
        """自定义日志格式"""
        logger.info(f"{self.address_string()} - {format % args}")

class WebServer:
    """MCP系统Web服务器"""
    
    def __init__(self, port=8090, directory=None):
        self.port = port
        self.directory = directory or os.getcwd()
        self.server = None
        self.server_thread = None
        
    def start(self, open_browser=True):
        """启动Web服务器"""
        try:
            # 切换到指定目录
            original_dir = os.getcwd()
            os.chdir(self.directory)
            
            # 创建服务器
            self.server = HTTPServer(('0.0.0.0', self.port), CORSHTTPRequestHandler)
            
            # 在后台线程中运行服务器
            self.server_thread = threading.Thread(target=self.server.serve_forever)
            self.server_thread.daemon = True
            self.server_thread.start()
            
            logger.info(f"Web服务器已启动: http://localhost:{self.port}")
            logger.info(f"服务目录: {self.directory}")
            
            # 检查index.html是否存在
            index_file = Path(self.directory) / "index.html"
            if index_file.exists():
                logger.info(f"主页面: http://localhost:{self.port}/index.html")
                
                # 自动打开浏览器
                if open_browser:
                    time.sleep(1)  # 等待服务器完全启动
                    try:
                        webbrowser.open(f"http://localhost:{self.port}/index.html")
                        logger.info("已自动打开浏览器")
                    except Exception as e:
                        logger.warning(f"无法自动打开浏览器: {e}")
            else:
                logger.warning(f"未找到index.html文件: {index_file}")
            
            return True
            
        except OSError as e:
            if e.errno == 48:  # Address already in use
                logger.error(f"端口 {self.port} 已被占用，请尝试其他端口")
            else:
                logger.error(f"启动Web服务器失败: {e}")
            return False
        except Exception as e:
            logger.error(f"启动Web服务器时发生错误: {e}")
            return False
    
    def stop(self):
        """停止Web服务器"""
        if self.server:
            logger.info("正在停止Web服务器...")
            self.server.shutdown()
            self.server.server_close()
            if self.server_thread:
                self.server_thread.join(timeout=5)
            logger.info("Web服务器已停止")
    
    def is_running(self):
        """检查服务器是否正在运行"""
        return self.server is not None and self.server_thread is not None and self.server_thread.is_alive()

def check_backend_services():
    """检查后端服务状态"""
    import requests
    
    services = [
        {"name": "MCP Generator", "url": "http://localhost:8010/health"},
        {"name": "MCP Server", "url": "http://localhost:8011/health"},
        {"name": "Agent Client", "url": "http://localhost:8080/health"}
    ]
    
    logger.info("检查后端服务状态...")
    all_running = True
    
    for service in services:
        try:
            response = requests.get(service["url"], timeout=3)
            if response.status_code == 200:
                logger.info(f"✅ {service['name']} - 运行正常")
            else:
                logger.warning(f"⚠️  {service['name']} - 状态码: {response.status_code}")
                all_running = False
        except requests.exceptions.RequestException:
            logger.error(f"❌ {service['name']} - 无法连接")
            all_running = False
    
    if not all_running:
        logger.warning("部分后端服务未运行，请先启动后端服务:")
        logger.warning("python scripts/start_all.py")
    
    return all_running

def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="MCP系统Web服务器")
    parser.add_argument("--port", "-p", type=int, default=8090, help="Web服务器端口 (默认: 8090)")
    parser.add_argument("--directory", "-d", type=str, help="服务目录 (默认: 当前目录)")
    parser.add_argument("--no-browser", action="store_true", help="不自动打开浏览器")
    parser.add_argument("--no-check", action="store_true", help="不检查后端服务状态")
    
    args = parser.parse_args()
    
    # 检查后端服务
    if not args.no_check:
        check_backend_services()
    
    # 创建并启动Web服务器
    web_server = WebServer(port=args.port, directory=args.directory)
    
    try:
        if web_server.start(open_browser=not args.no_browser):
            logger.info("Web服务器运行中，按 Ctrl+C 停止服务器")
            
            # 保持服务器运行
            while web_server.is_running():
                time.sleep(1)
        else:
            logger.error("Web服务器启动失败")
            sys.exit(1)
            
    except KeyboardInterrupt:
        logger.info("接收到中断信号")
    except Exception as e:
        logger.error(f"运行时错误: {e}")
    finally:
        web_server.stop()
        logger.info("程序退出")

if __name__ == "__main__":
    main()
